//
//  message_SystemView.m
//  SoundPill
//
//  Created by 宋旭东 on 16/4/20.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "message_SystemView.h"
#import "UIViewExt.h"
#import "WZLBadgeImport.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "messageSystemTableViewCell.h"
#import "systemMessageModel.h"
@interface message_SystemView ()<MJRefreshBaseViewDelegate>
{
    int currentPage;
    int pages;
    MJRefreshFooterView *footer;
}
@end

@implementation message_SystemView
//message/get?uid=
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataArray = [[NSMutableArray alloc] init];
        currentPage = 1;
        [self createSubviews];
        [self requestDataWithPage:currentPage refreshView:footer];
    }
    return self;
}
- (void)requestDataWithPage:(int)page refreshView:(MJRefreshFooterView *)refreshview
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *userheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:userheader forHTTPHeaderField:@"authorization"];
    NSString *urlStr=[NSString stringWithFormat:@"http://123.57.1.143/api/message/get?p=%d",page];
    [manager POST:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self reloadSelfData:responseObject pag:page];
        [refreshview endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)reloadSelfData:(id)responseObject pag:(int)pag
{
    NSDictionary *data = [responseObject valueForKey:@"data"];
    for (NSDictionary *dic in data) {
        systemMessageModel *model = [[systemMessageModel alloc] init];
//        [systemMessageModel setValuesForKeysWithDictionary:dic];
        model.action = [dic valueForKey:@"action"];
        model.avatar = [dic valueForKey:@"avatar"];
        model.created_at = [dic valueForKey:@"created_at"];
        model.id = [dic valueForKey:@"id"];
        model.isread = [dic valueForKey:@"isread"];
        model.message = [dic valueForKey:@"message"];
        model.type = [dic valueForKey:@"type"];
        model.userid = [dic valueForKey:@"userid"];
        model.username = [dic valueForKey:@"username"];
        if (![model.action isEqualToString:@"people"]) {
            model.workid = [dic valueForKey:@"workid"];
        } else {
            model.follow = [dic valueForKey:@"follow"];
        }
        [_dataArray addObject:model];
    }
    NSDictionary *meta = [responseObject valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            footer.hidden = YES;
        }
    }
    [_tableview reloadData];
}
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshSystemHeaderView class]];
    if (isHeader) {
        currentPage = 1; // 第一页
        footer.hidden = NO;
        [_dataArray removeAllObjects];
//        [self AFNetworking:page uid:_selfUid refreshing:refreshView];
//        [_HeaderInfor requestOwnInfor:_selfUid];
    }else { // 上拉加载更多
        if (pages == 1 || currentPage == pages) {
            footer.hidden = YES;
        } else {
            currentPage++;
            [self requestDataWithPage:currentPage refreshView:footer];
        }
    }
}
- (void)createSubviews
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //    _tableview.backgroundColor = [UIColor grayColor];
    [self addSubview:_tableview];
    
    footer = [MJRefreshFooterView footer];
    footer.scrollView = _tableview;
    footer.delegate = self;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ([UIScreen mainScreen].bounds.size.height - 64 - 45) / 8;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  NO;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return   UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"system";
    // 检查表视图中是否存在闲置的单元格
    messageSystemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[messageSystemTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    __weak typeof(cell) weakcell = cell;
    cell.model = _dataArray[indexPath.row];
    cell.separatorColor = tableView.separatorColor;
    cell.block = ^(NSString *action,NSString *userid) {
        _block(action,weakcell.model.userid,nil);
    };
    cell.actBlock = ^(NSUInteger index){
      systemMessageModel *model = _dataArray[indexPath.row];
        switch (index) {
            case 0:
                model.follow = @"1";
                break;
            case 1:
                model.action = @"payed";
                break;
            case 2:
                 model.action = @"loved";
                break;
                
            default:
                break;
        }
        [tableView reloadData];
    };
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    messageSystemTableViewCell *cell = (messageSystemTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.redView.hidden = YES;
    systemMessageModel *model = _dataArray[indexPath.row];
    model.isread = @"1";
    _block(model.action,model.userid,model.workid);
}

@end
